package com.fun.feifun.modules.business.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fun.feifun.base.result.Result;
import com.fun.feifun.base.utils.ControlUtils;
import com.fun.feifun.base.utils.RedisUtil;
import com.fun.feifun.base.utils.format.FormatUtil;
import com.fun.feifun.modules.business.model.BusinessGoods;
import com.fun.feifun.modules.business.model.BusinessOrder;
import com.fun.feifun.modules.business.model.BusinessUser;
import com.fun.feifun.modules.business.model.param.BusinessApiBackParam;
import com.fun.feifun.modules.business.model.dto.BusinessApiOrderInfoDto;
import com.fun.feifun.modules.business.model.dto.BusinessApiUserAmtDto;
import com.fun.feifun.modules.business.model.param.BusinessPlaceOrderParam;
import com.fun.feifun.modules.business.model.param.BusinessGetOrderParam;
import com.fun.feifun.modules.business.model.param.BusinessGetUserAmtParam;
import com.fun.feifun.modules.business.service.*;
import com.fun.feifun.modules.sys.parameter.service.ISysParameterService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * <p>
 * 业务供应商 前端控制器
 * </p>
 *
 * @author wkf
 * @since 2024-06-04
 */
@RestController
@Api(value = "/business/user-api", tags = "API-用户")
@Slf4j
@RequestMapping("/business/user-api")
public class BusinessUserAPIController {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private IBusinessOrderService service;
    @Autowired
    private IBusinessUserService businessUserService;
    @Autowired
    private IBusinessSupplierService supplierService;
    @Autowired
    private IBusinessGoodsService businessGoodsService;
    @Autowired
    private IBusinessUserGoodsService userGoodsService;
    @Autowired
    private IBusinessUserService userService;
    @Autowired
    private ISysParameterService parameterService;
    @Autowired
    private IBusinessOrderLogService logService;
    @Autowired
    private IBusinessBlacklistService blacklistService;

    @Resource
    private RedisUtil redisUtil;


    @PostMapping(value = "/placeOrderOutside")
    @ApiOperation(value = "用户-话费订单提交接口")
    public Result<String> placeOrder(@RequestBody BusinessPlaceOrderParam param) {
        try {
            String pattern = "^1[3456789]\\d{9}$";
            boolean matches = Pattern.matches(pattern, param.getMobile());
            if(!matches){
                throw new RuntimeException("充值号码，校验不同过请检查是否是手机号");
            }
            Object o = redisUtil.get("blacklist:"+param.getMobile());
            if(o!=null){
                throw new RuntimeException(param.getMobile()+"已被拉入黑名单，请24小小时后尝试。");
            }
            String nowSign = param.MD5Sign();
//            if(!nowSign.equals(param.getSign())){
//                throw new RuntimeException("加密密匙不一致");
//            }
            QueryWrapper<BusinessUser> wrapper=new QueryWrapper<>();
            wrapper.lambda().eq(BusinessUser::getCode,param.getUserid());
            BusinessUser user = businessUserService.getOne(wrapper);
            if(ObjectUtils.isEmpty(user)){
                throw new RuntimeException("代理用户不存在");
            }
            if(!ControlUtils.isNotEmpty(user.getSecretKey())){
                throw new RuntimeException("代理用户未生成密匙");
            }
            if(!user.getSecretKey().equals(param.getKey())){
                throw new RuntimeException("代理用户的密匙不一致");
            }
            QueryWrapper<BusinessGoods> goodsWrapper=new QueryWrapper<>();
            goodsWrapper.lambda().eq(BusinessGoods::getCode,param.getProductid());
            BusinessGoods goods = businessGoodsService.getOne(goodsWrapper);
            if(ObjectUtils.isEmpty(goods)){
                throw new RuntimeException("商品不存在");
            }
            if(param.getPrice()!=goods.getAmount().intValue()){
                throw new RuntimeException("商品价格与充值价格不一致");
            }
            service.placeOrder(goods, user, param);
            return Result.success("下单成功！");
        }catch (Exception e){
            e.printStackTrace();
            blacklistService.add(param.getMobile());
            throw new RuntimeException(e.getMessage());
        }
    }

    @PostMapping(value = "/getOrder")
    @ApiOperation(value = "用户-订单查询接口")
    public Result<BusinessApiOrderInfoDto> getOrder(@RequestBody BusinessGetOrderParam param) {
        String nowSign = param.MD5Sign();
//        if(!nowSign.equals(param.getSign())){
//            throw new RuntimeException("加密密匙不一致");
//        }
        QueryWrapper<BusinessUser> wrapper=new QueryWrapper<>();
        wrapper.lambda().eq(BusinessUser::getCode,param.getUserid());
        BusinessUser user = userService.getOne(wrapper);
        if(ObjectUtils.isEmpty(user)){
            throw new RuntimeException("代理用户不存在");
        }
        if(!ControlUtils.isNotEmpty(user.getSecretKey())){
            throw new RuntimeException("代理用户未生成密匙");
        }
        if(!user.getSecretKey().equals(param.getKey())){
            throw new RuntimeException("代理用户的密匙不一致");
        }
        QueryWrapper<BusinessOrder> orderQueryWrapper=new QueryWrapper<>();
        orderQueryWrapper.lambda().eq(BusinessOrder::getCode,param.getSporderid());
        BusinessOrder order = service.getOne(orderQueryWrapper);
        if(ObjectUtils.isEmpty(order)){
            throw new RuntimeException("【"+param.getSporderid()+"】订单号的订单不存在，请检查");
        }
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("code",order.getCode());
            map.put("rechargeAccount",order.getRechargeAccount());
            map.put("goodsCode",order.getGoodsCode());
            map.put("goodsName",order.getGoodsName());
            map.put("goodsAmount",order.getGoodsAmount());
            map.put("state",order.getState());
            map.put("payState",order.getPayState());
            map.put("businessUserCode",order.getBusinessUserCode());
            map.put("businessUserNike",order.getBusinessUserNike());
            map.put("remake",order.getRemake());
            String xml =FormatUtil.mapToXML(map,"order");
            BusinessApiOrderInfoDto dto=new BusinessApiOrderInfoDto();
            dto.setOrderCode(order.getCode());
            dto.setRechargeAccount(order.getRechargeAccount());
            dto.setGoodsCode(order.getGoodsCode());
            dto.setGoodsName(order.getGoodsName());
            dto.setGoodsAmount(order.getGoodsAmount());
            dto.setBusinessUserCode(order.getBusinessUserCode());
            dto.setBusinessUserNike(order.getBusinessUserNike());
            dto.setPayState(order.getPayState());
            dto.setRemake(order.getRemake());
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            dto.setPayTime(order.getCreateTime().format(formatter));
            return Result.success(dto);
        }catch (Exception exception){
            throw new RuntimeException(exception.getMessage());
        }
    }

    @PostMapping(value = "/getUserAmount")
    @ApiOperation(value = "用户-余额查询")
    public Result<BusinessApiUserAmtDto> getUserAmount(@RequestBody BusinessGetUserAmtParam param) {
        String nowSign = param.MD5Sign();
//        if(!nowSign.equals(param.getSign())){
//            throw new RuntimeException("加密密匙不一致");
//        }
        QueryWrapper<BusinessUser> wrapper=new QueryWrapper<>();
        wrapper.lambda().eq(BusinessUser::getCode,param.getUserid());
        BusinessUser user = userService.getOne(wrapper);
        if(ObjectUtils.isEmpty(user)){
            throw new RuntimeException("代理用户不存在");
        }
        if(!ControlUtils.isNotEmpty(user.getSecretKey())){
            throw new RuntimeException("代理用户未生成密匙");
        }
        if(!user.getSecretKey().equals(param.getKey())){
            throw new RuntimeException("代理用户的密匙不一致");
        }
        try {
            BusinessApiUserAmtDto dto = new BusinessApiUserAmtDto();
            dto.setCode(user.getCode());
            dto.setName(user.getUserName());
            dto.setAmount(user.getAmount());
            dto.setCreditAmount(user.getCreditAmount());
            return Result.success(dto);
        }catch (Exception exception){
            throw new RuntimeException(exception.getMessage());
        }
    }

    @PostMapping(value = "/back_url")
    @ApiOperation(value = "回调接口-参数示意(我返回给你的参数)")
    public @ApiModelProperty("请返回一个 \"ok\" (字符串)表示收到")String back_url(@RequestBody BusinessApiOrderInfoDto param) {
        return "ok";
    }


}

